<template>
  <div class="admin-manage-container">
    <div class="admin-header">
      <h2>用户管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="refreshUserList">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 用户列表 -->
    <div class="user-list-section">
      <el-table 
        :data="userList" 
        style="width: 100%" 
        v-loading="loading"
        stripe
        border
      >
        <el-table-column prop="id" label="用户ID" width="80" />
        <el-table-column prop="username" label="用户名" width="150" />
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="phone" label="手机号" width="150" />
        <el-table-column prop="role" label="角色" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.role === 'admin' ? 'danger' : 'primary'">
              {{ scope.row.role === 1 ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="updateTime" label="更新时间" width="180" />
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="scope">
            <div class="action-buttons">
              <el-button 
                type="primary" 
                size="small" 
                @click="viewUser(scope.row)"
              >
                查看
              </el-button>
              <el-button 
                type="warning" 
                size="small" 
                @click="editUser(scope.row)"
              >
                编辑
              </el-button>
              <el-button 
                type="danger" 
                size="small" 
                @click="deleteUser(scope.row)"
                :disabled="scope.row.role === 'admin'"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 用户详情对话框 -->
    <el-dialog 
      v-model="userDetailVisible" 
      title="用户详情" 
      width="600px"
    >
      <div v-if="selectedUser" class="user-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="用户ID">{{ selectedUser.id }}</el-descriptions-item>
          <el-descriptions-item label="用户名">{{ selectedUser.username }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ selectedUser.email }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{ selectedUser.phone }}</el-descriptions-item>
          <el-descriptions-item label="角色">
            <el-tag :type="selectedUser.role === 1 ? 'danger' : 'primary'">
              {{ selectedUser.role === 1 ? '管理员' : '普通用户' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ selectedUser.createTime }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ selectedUser.updateTime }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog 
      v-model="editUserVisible" 
      title="编辑用户" 
      width="600px"
    >
      <div class="edit-tip">
        <el-alert
          title="提示：只需填写要修改的字段，空白字段将保持原值不变"
          type="info"
          :closable="false"
          show-icon
        />
      </div>
      <el-form 
        ref="editFormRef" 
        :model="editForm" 
        :rules="editRules" 
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="editForm.username" 
            placeholder="留空则不修改用户名" 
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input 
            v-model="editForm.email" 
            placeholder="留空则不修改邮箱" 
            maxlength="50"
            type="email"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input 
            v-model="editForm.phone" 
            placeholder="留空则不修改手机号" 
            maxlength="11"
            @input="handlePhoneInput"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="editForm.role" placeholder="请选择角色">
            <el-option label="普通用户" :value="0" />
            <el-option label="管理员" :value="1" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editUserVisible = false">取消</el-button>
          <el-button type="primary" @click="saveUser" :loading="saving">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { getAllUsersApi, getUserByIdApi, updateUserApi, deleteUserApi } from '../apis/adminAPI.js'

// 路由实例
const router = useRouter()

// 响应式数据
const userList = ref([])
const loading = ref(false)
const userDetailVisible = ref(false)
const editUserVisible = ref(false)
const selectedUser = ref(null)
const saving = ref(false)

// 编辑表单
const editForm = ref({
  id: null,
  username: '',
  email: '',
  phone: '',
  role: 'user'
})

const editFormRef = ref()

// 表单验证规则
const editRules = {
  username: [
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/, message: '用户名只能包含字母、数字、下划线和中文', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, message: '邮箱格式不正确', trigger: 'blur' },
    { max: 50, message: '邮箱长度不能超过50个字符', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的11位手机号码', trigger: 'blur' },
    { len: 11, message: '手机号必须为11位数字', trigger: 'blur' }
  ]
}

// 获取所有用户列表
const getAllUsers = async () => {
  loading.value = true
  try {
    const response = await getAllUsersApi()
    if (response.code === 200) {
      userList.value = response.data || []
    } else if (response.code === 403) {
      ElMessage.error(response.msg || '权限不足，仅管理员可操作')
      // 权限不足时跳转到首页
      router.push('/')
    } else {
      ElMessage.error(response.msg || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('网络请求失败，请稍后再试')
  } finally {
    loading.value = false
  }
}

// 刷新用户列表
const refreshUserList = () => {
  getAllUsers()
}

// 查看用户详情
const viewUser = async (user) => {
  try {
    const response = await getUserByIdApi(user.id)
    console.log(response) // 打印完整的response inf
    if (response.code === 200) {
      selectedUser.value = response.data
      userDetailVisible.value = true
    } else if (response.code === 403) {
      ElMessage.error(response.msg || '权限不足，仅管理员可操作')
      router.push('/')
    } else if (response.code === 400) {
      ElMessage.error(response.msg || '用户ID无效')
    } else if (response.code === 404) {
      ElMessage.error(response.msg || '用户不存在')
    } else {
      ElMessage.error(response.msg || '获取用户详情失败')
    }
  } catch (error) {
    console.error('获取用户详情失败:', error)
    ElMessage.error('网络请求失败，请稍后再试')
  }
}

// 编辑用户
const editUser = (user) => {
  editForm.value = {
    id: user.id,
    username: '',
    email: '',
    phone: '',
    role: user.role // 保留原角色作为默认值
  }
  editUserVisible.value = true
}

// 保存用户
const saveUser = async () => {
  if (!editFormRef.value) return
  
  try {
    await editFormRef.value.validate()
    saving.value = true
    
    // 只发送有值的字段
    const updateData = { id: editForm.value.id }
    if (editForm.value.username && editForm.value.username.trim()) {
      updateData.username = editForm.value.username.trim()
    }
    if (editForm.value.email && editForm.value.email.trim()) {
      updateData.email = editForm.value.email.trim()
    }
    if (editForm.value.phone && editForm.value.phone.trim()) {
      updateData.phone = editForm.value.phone.trim()
    }
    if (editForm.value.role !== null && editForm.value.role !== undefined) {
      updateData.role = editForm.value.role
    }
    
    const response = await updateUserApi(editForm.value.id, updateData)
    if (response.code === 200) {
      ElMessage.success(response.msg || '更新成功')
      editUserVisible.value = false
      await getAllUsers() // 刷新列表
    } else if (response.code === 403) {
      ElMessage.error(response.msg || '权限不足，仅管理员可操作')
      router.push('/')
    } else if (response.code === 400) {
      if (response.msg && response.msg.includes('账号已存在')) {
        ElMessage.error(response.msg || '账号已存在')
      } else {
        ElMessage.error(response.msg || '用户ID无效')
      }
    } else if (response.code === 404) {
      ElMessage.error(response.msg || '用户不存在')
    } else if (response.code === 500) {
      ElMessage.error(response.msg || '更新失败')
    } else {
      ElMessage.error(response.msg || '更新用户信息失败')
    }
  } catch (error) {
    if (error !== false) { // 不是表单验证错误
      console.error('更新用户信息失败:', error)
      ElMessage.error('网络请求失败，请稍后再试')
    }
  } finally {
    saving.value = false
  }
}

// 删除用户
const deleteUser = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${user.username}" 吗？此操作不可恢复。`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const response = await deleteUserApi(user.id)
    if (response.code === 200) {
      ElMessage.success(response.msg || '删除成功')
      await getAllUsers() // 刷新列表
    } else if (response.code === 403) {
      ElMessage.error(response.msg || '权限不足，仅管理员可操作')
      router.push('/')
    } else if (response.code === 400) {
      if (response.msg && response.msg.includes('不能删除自己的账号')) {
        ElMessage.error(response.msg || '不能删除自己的账号')
      } else {
        ElMessage.error(response.msg || '用户ID无效')
      }
    } else if (response.code === 404) {
      ElMessage.error(response.msg || '用户不存在')
    } else if (response.code === 500) {
      ElMessage.error(response.msg || '删除失败')
    } else {
      ElMessage.error(response.msg || '删除用户失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error)
      ElMessage.error('网络请求失败，请稍后再试')
    }
  }
}

// 处理手机号输入，只允许数字
const handlePhoneInput = (value) => {
  // 移除所有非数字字符
  const numericValue = value.replace(/\D/g, '')
  editForm.value.phone = numericValue
}

// 组件挂载时获取用户列表
onMounted(() => {
  getAllUsers()
})
</script>

<style scoped>
.admin-manage-container {
  min-height: calc(100vh - 105px);
  margin-bottom: 60px;
  background: linear-gradient(135deg, #e3f2fd 0%, #ffffff 100%);
  padding: 20px;
}

.admin-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.admin-header h2 {
  margin: 0;
  color: #2c3e50;
  font-size: 24px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.user-list-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.user-detail {
  padding: 10px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
  justify-content: flex-start;
  flex-wrap: nowrap;
}

.action-buttons .el-button {
  margin: 0;
  min-width: 60px;
}

.edit-tip {
  margin-bottom: 20px;
}

.edit-tip .el-alert {
  border-radius: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .admin-manage-container {
    min-height: calc(100vh - 95px);
    margin-bottom: 50px;
    padding: 10px;
  }
  
  .admin-header {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }
  
  .user-list-section {
    padding: 15px;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 5px;
    align-items: stretch;
  }
  
  .action-buttons .el-button {
    min-width: auto;
    width: 100%;
  }
}
</style>